<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option label="区域一" value="shanghai"></el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small">筛选</el-button>
            <el-button type="info" size="small">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubVisible = true">发表文章</el-button>
      </div>
      <!-- 文章表格区域 -->
      <!-- 分页区域 -->
    </el-card>
    <!-- 发表文章的对话框 -->
    <el-dialog title="发表文章" :visible.sync="pubVisible" fullscreen :before-close="beforeClose" @closed="pubClosed">
      <!-- 发表文章的表单 -->
      <el-form :model="pubForm" :rules="pubRules" ref="pubRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
            <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容">
          <!-- 使用 v-model 进行双向的数据绑定 -->
          <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none;" accept="image/*" ref="fileRef" @change="fileChange" />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="chooseImg">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pubArticle('已发布')">发布</el-button>
          <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看文章详情的对话框 -->
  </div>
</template>

<script>
import img from '@/assets/images/cover.jpg'
console.log(img)
export default {
  name: 'ArtList',
  data() {
    return {
      // 查询参数对象
      q: {
        // 当前是第几页
        pagenum: 1,
        // 每页展示多少条
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      // 控制发表文章的显示与隐藏
      pubVisible: false,
      // 表单的数据对象
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: null,
        state: ''
      },
      // 表单的验证规则对象
      pubRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请选择文章标题', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请填写文章内容', trigger: 'blur' }
        ],
        cover_img: [
          { required: true, message: '请填写文章内容', trigger: 'blur' }
        ]
      },
      // 文章分类列表
      cateList: []
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 对话框关闭之前的回调函数
    beforeClose() {
      // 询问用户是否确认关闭对话框
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确定按钮，会走 then
        this.pubVisible = false
      }).catch(() => {
        // 点击取消按钮，会走 catch
      })
    },
    // 获取文章分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('/my/cate/list')
      if (res.code === 0) {
        this.cateList = res.data
      }
    },
    // 模拟图片点击
    chooseImg() {
      this.$refs.fileRef.click()
    },
    // 选择图片后
    fileChange(e) {
      const files = e.target.files
      console.log(files)
      if (files.length === 0) {
        // this.pubForm.cover_img = null
      } else {
        this.pubForm.cover_img = files[0]
        console.log(files[0])
        const url = URL.createObjectURL(files[0])
        // console.log(url)
        this.$refs.imgRef.setAttribute('src', url)
      }
    },
    // 关闭对话框，重置表单
    pubClosed() {
      this.$refs.pubRef.resetFields()
      this.pubForm.content = ''
      this.pubForm.cover_img = null
      this.pubForm.state = ''
      this.$refs.imgRef.setAttribute('src', img)
    },
    // 发布文章或草稿
    pubArticle(state) {
      // 设置发布状态
      this.pubForm.state = state
      // 1. 表单预校验
      this.$refs.pubRef.validate(async valid => {
        // 为有校验规则的表单项的验证
        if (!valid) {
          this.$message.error('请填写文章标题和分类！')
          return
        }
        // 其他表单项验证
        if (this.pubForm.content === '') {
          this.$message.error('请填写文章内容！')
          return
        }
        if (this.pubForm.cover_img === null) {
          this.$message.error('请选择文章封面！')
          return
        }
        console.log('ok')
        // 2. 发起请求
        // 把普通的对象转为 formdata 格式的对象
        // 创建 FormData 对象
        const fd = new FormData()
        // 向 FormData 中追加数据
        // fd.append('title', this.pubForm.title)
        // fd.append('cate_id', this.pubForm.cate_id)
        // fd.append('content', this.pubForm.content)
        // fd.append('cover_img', this.pubForm.cover_img)
        // fd.append('state', this.pubForm.state)
        // for (const key in this.pubForm) {
        //   fd.append(key, this.pubForm[key])
        // }
        Object.keys(this.pubForm).forEach(key => {
          fd.append(key, this.pubForm[key])
        })
        // 发起请求
        const { data: res } = await this.$http.post('/my/article/add', fd)
        if (res.code === 0) {
          this.$message.success('发布文章成功！')
          // 关闭对话框
          this.pubVisible = false
          // TODO：刷新文章列表数据
        } else {
          this.$message.error('发布文章失败！')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
</style>
